import pdb

from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
from django.http import HttpResponse

from lists.models import Item, List
from lists.forms import ItemForm, ExistingListItemForm

def home_page(request):
    # print(request.META.get('HTTP_USER_AGENT'))
    list_all = List.objects.all()
    form_ = ItemForm()
    return render(request, 'home.html',
                  {'lists': list_all,
                   'form': form_
               })


def view_list(request, list_id):
    list_all = List.objects.all()
    list_ = List.objects.get(pk=list_id)
    form = ExistingListItemForm(for_list=list_)
    if request.method == "POST":
        form = ExistingListItemForm(for_list=list_,
                                    data=request.POST)
        if form.is_valid():
            # item = Item(text=request.POST['text'], list=list_)
            # item.save()
            #form.save(for_list=list_)
            form.save()
            #return redirect('/lists/%d/' % (list_.id,))
            return redirect(list_)
            # Item.objects.create(text=request.POST['item_text'], list=list_)
            # #items = Item.objects.filter(list=list_)
            # return redirect('/lists/%d/' % (list_.id,))
    return render(request, 'list.html',
                  {'lists': list_all,'list': list_,'form': form,}
              )


def new_list(request):
    form = ItemForm(data=request.POST)
    #if request.method == "POST" and request.POST.get('text').strip():
    #if request.method == "POST":
    if form.is_valid():
        list_ = List.objects.create()
        form.save(for_list=list_)
        return redirect(list_)
    else:
        #return redirect(reverse('home'))
        return render(request, 'home.html', {'form': form})

# def add_item(request, list_id):
#     list_ = List.objects.get(id=list_id)
#     Item.objects.create(text=request.POST['item_text'], list=list_)
#     return redirect('/lists/%d/' % (list_.id,))

